package com.fanshuai.jmx.client;

import javax.management.Attribute;
import javax.management.MBeanServerConnection;
import javax.management.ObjectName;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;

public class RMIClient {
    public static void init() throws Exception {
        JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:1999/jmxrmi");
        JMXConnector connector = JMXConnectorFactory.newJMXConnector(url, null);

        MBeanServerConnection connection = connector.getMBeanServerConnection();

        ObjectName objectName = new ObjectName("custom:name=hello");

        //domains
        String[] domains = connection.getDomains();
        System.out.println("domains=" + domains);

        int mBeanCount = connection.getMBeanCount();
        System.out.println("mBean count=" + mBeanCount);

        //get attr
        int age = (int) connection.getAttribute(objectName, "Age");
        System.out.println("age=" + age);

        //set attr
        connection.setAttribute(objectName, new Attribute("Name", "阿狸"));

        //调用MBean方法
        connection.invoke(objectName, "hello", null, null);
    }
}
